package Jcat.cduestcbbs.Servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Jcat.cduestcbbs.Po.UserPo;
import Jcat.cduestcbbs.Service.RegisterService;

import javax.servlet.http.HttpSession;

public class RegisterServlet {
	private static final long serialVersionUID = 1L;
	private RegisterService registerservice = new RegisterService();

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		register(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		register(req, resp);
	}

	private void register(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		UserPo user = new UserPo();
		user.setUserName((String) req.getParameter("person_name"));
		user.setUserPassword((String) req.getParameter("person_password"));
		user.setUserEmail((String) req.getParameter("email"));
		user.setUserNickName((String) req.getParameter("nickname"));
		user.setUserCommuncation((String) req
				.getParameter("person_communcation"));
		user.setUserAdrress((String) req.getParameter("person_from"));
		user.setUserNumber((String) req.getParameter("person_number"));

		user.setUserSelfIntrodustion((String) req
				.getParameter("person_self_introduction"));
		user.setUserSex((String) req.getParameter("sex"));
		user.setUserSafeQuestion((String) req.getParameter("safequestion"));
		user.setUserSafeQuestionAnswer((String) req
				.getParameter("userSafeQuestionAnswer"));

		user.setUserRegisterTime((String) req.getParameter("userRegisterTime"));

		boolean register;

		HttpSession session = req.getSession();

		register = registerservice.insertUser(user);

		if (register == true) {
			session.setAttribute("user", user);
			req.setAttribute("user", user);
			RequestDispatcher rs = req.getRequestDispatcher("success.jsp");
			try {
				rs.forward(req, resp);
			} catch (ServletException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		} else {
			String error = registerservice.errorMessage(user);
			req.setAttribute("error", error);

			req.getRequestDispatcher("register.jsp");

		}
	}
}